package dycloud.GameName.mongoDB.controller;



import com.alibaba.fastjson.JSON;
import dycloud.demo.model.JsonResponse;
import dycloud.GameName.mongoDB.service.MongoDBService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
public class MongoDBCtrl {


    @Autowired
    private MongoDBService mongoService;



    /**
     * 获取当前有哪些数据库集合
     * GET /mongo/collections
     * @return 集合名称列表
     */
    @GetMapping("/collections")
    public JsonResponse getAllCollections() {
        JsonResponse response = new JsonResponse();
        List<String> collections = mongoService.getAllCollections();
        if (collections.isEmpty()) {
            response.failure("没有找到任何集合");
            return response;
        } else {
            response.success(JSON.toJSONString(collections) );
            return response;
        }
    }


    /**
     * 获取集合内的数据
     * GET /mongo/collections/{collectionName}
     * @param collectionName 集合名称
     * @return 集合内的数据
     */
    @GetMapping("/collections/{collectionName}")
    public JsonResponse getCollectionData(@PathVariable String collectionName) {
        JsonResponse response = new JsonResponse();
        List<Object> data = mongoService.getCollectionData(collectionName, Object.class);
        if (data.isEmpty()) {
            response.failure("集合 " + collectionName + " 内没有数据");
        } else {
            response.success(JSON.toJSONString(data));
        }
        return response;
    }


    /**
     * 删除指定集合
     * DELETE /mongo/collections/{collectionName}
     * @param collectionName 集合名称
     * @return 删除结果
     */
    @DeleteMapping("/collections/{collectionName}")
    public JsonResponse deleteCollection(@PathVariable String collectionName) {
        JsonResponse response = new JsonResponse();
        boolean isDeleted = mongoService.deleteCollection(collectionName);
        if (isDeleted) {
            response.success("集合 " + collectionName + " 删除成功");
        } else {
            response.failure("集合 " + collectionName + " 删除失败");
        }
        return response;
    }

    /**
     * 删除所有集合
     * DELETE /mongo/collections
     * @return 删除结果
     */
    @DeleteMapping("/collections")
    public JsonResponse deleteAllCollections() {
        JsonResponse response = new JsonResponse();
        boolean isDeleted = mongoService.deleteAllCollections();
        if (isDeleted) {
            response.success("所有集合删除成功");
        } else {
            response.failure("所有集合删除失败");
        }
        return response;
    }


}
